package fr.sedoo.sos.xml;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import net.opengis.gml.x32.TimeInstantPropertyType;
import net.opengis.gml.x32.TimePeriodDocument;
import net.opengis.gml.x32.TimePeriodType;
import net.opengis.om.x20.OMObservationType;
import net.opengis.om.x20.TimeObjectPropertyType;
import net.opengis.sos.x20.InsertObservationDocument;
import net.opengis.sos.x20.InsertObservationType;

import org.apache.xmlbeans.XmlAnyURI;

import fr.sedoo.sos.domain.Serie;
import fr.sedoo.sssdata.server.sos.GosudConstants;
import fr.sedoo.sssdata.server.sos.SensorMLConstants;
import fr.sedoo.sssdata.server.sos.XmlBeansUtils;

public class ObservationUtils {

	public static String getInsertObservationRequest(Serie serie)
	{
		InsertObservationDocument insertObservationDocument = InsertObservationDocument.Factory.newInstance();
		InsertObservationType insertObservation = insertObservationDocument.addNewInsertObservation();
		insertObservation.setService(SensorMLConstants.SOS);
		insertObservation.setVersion(SensorMLConstants.VERSION);
		
		XmlAnyURI sensorOffering = insertObservation.addNewOffering();
		sensorOffering.setStringValue(serie.getSensor().getOffering());
		
		XmlAnyURI stationOffering = insertObservation.addNewOffering();
		stationOffering.setStringValue(serie.getSensor().getStation().getOffering());

		OMObservationType omObservation = insertObservation.addNewObservation().addNewOMObservation();
		omObservation.addNewType().setHref(SosConstants.OM_MEASUREMENT_TYPE);
		
		TimeObjectPropertyType phenomenonTime = omObservation.addNewPhenomenonTime();
		TimePeriodDocument timePeriodDocument = TimePeriodDocument.Factory.newInstance();
		TimePeriodType timePeriod = timePeriodDocument.addNewTimePeriod();
		
		String beginTime = OgcUtils.format(serie.getBeginDate());
		String endTime = OgcUtils.format(serie.getEndDate());
		
		timePeriod.addNewBeginPosition().setStringValue(beginTime);
		timePeriod.addNewEndPosition().setStringValue(endTime);
		String phenomenonTimeId = "phenomenonTime";
		timePeriod.setId(phenomenonTimeId);
		phenomenonTime.set(timePeriodDocument);
		
		
		TimeInstantPropertyType resultTime = omObservation.addNewResultTime();
		resultTime.setHref("#"+phenomenonTimeId);
		
		
		//TODO gml:id sur OM_Observation
		
		return XmlBeansUtils.toString(insertObservationDocument);
		
	}
	
}
